//
//  CZOAuthViewController.swift
//  WHWeiBo01
//
//  Created by whitcast on 16/7/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking

//  微博appKey
let WeiboAppKey = "1182785320"
//  微博appsecret
let WeiboAppSecret = "1606843f6c67acf9cd0771db17fc1ac2"
//  微博授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"


class CZOAuthViewController: UIViewController {
    
    // MARK:    --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  自定义视图
        webView.delegate = self
        //  默认不透明,改成透明
        webView.opaque = false
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        requestOAuthLogin()
    }
    
    private func requestOAuthLogin() {
        //  请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        //  准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //  加载请求
        webView.loadRequest(request)
    
    }
    
    
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    
    }
    
    // MARK: -- 点击事件
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        print("自动填充")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
    }
    
    //  代码已经抽取CZUserAccountViewModel
    
//    //  通过授权码(code)获取accesstoken
//    private func requestAccesstoken(code: String) {
//        
//        CZNetworkTools.sharedToos.requestAccesstoken(code) { (response, error) -> () in
//            
//            if error != nil {
//                print(error)
//                return
//            }
//            
//            //  代码执行到此,成功的回调
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json格式")
//                return
//            }
//
//            //  代码执行到此, dic一定有值,并且是符合我们需要的类型
//
//            let userAccount = CZUserAccount(dic: dic)
//            //print(userAccount.uid, userAccount.access_token)
//            print(userAccount)
//            
//            //  通过accessToken和uid获取用户信息
//            self.requestUserInfo(userAccount)
//            
//
//            
//        }
//        
//        
//        
//        
//        
//        
//        
//        
//        
//        
////        //  准备接口地址
////        let url = "https://api.weibo.com/oauth2/access_token"
////        //  准备参数
////        let params = [
////            "client_id": WeiboAppKey,
////            "client_secret": WeiboAppSecret,
////            "grant_type": "authorization_code",
////            "code": code,
////            "redirect_uri": WeiboRedirect_Uri
////        ]
////        
////        CZNetworkTools.sharedToos.request(.POST, url: url, params: params) { (response, error) -> () in
////            
////            if error != nil {
////                //  代表的是失败的回调
////                print(error)
////                return
////            }
////            //  代码执行到此是成功的回调
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确的字典格式")
////                return
////            }
////            
////            let userAccount = CZUserAccount(dic: dic)
////            print(userAccount)
////            
////            
////            
////            
////        }
//        
//        
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        //  发送post
////        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确的json格式")
////                return
////            }
////            
////            //  代码执行到此, dic一定有值,并且是符合我们需要的类型
////            
////            let userAccount = CZUserAccount(dic: dic)
////            //print(userAccount.uid, userAccount.access_token)
////            print(userAccount)
////            
////            //  通过accessToken和uid获取用户信息
////            self.requestUserInfo(userAccount)
////            
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//        
//    
//    }
    
//    //  获取用户信息
//    private func requestUserInfo(userAccount: CZUserAccount) {
//        
//        
//        CZNetworkTools.sharedToos.requestUserInfo(userAccount) { (response, error) -> () in
//            
//            if error != nil {
//                print(error)
//                return
//            }
//            
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确json格式")
//                return
//            }
//
//            //  代码执行到此字典一定有值
//
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//
//            //  设置用户名和头像
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            //  保存用户对象
//            userAccount.saveUserAccount()
//            print(userAccount)
//        }
//        
//        
//        
//        
////        //  请求接口地址
////        let url = "https://api.weibo.com/2/users/show.json"
////        //  准备请求参数
////        //  int64,跟字符串放在一起编译不通过,需要转换成字符串
////        let params = [
////            "access_token": userAccount.access_token!,
////            "uid": "\(userAccount.uid)"
////        ]
////        
////        let urlStr = url + "?access_token=\(userAccount.access_token!)&uid=\(userAccount.uid)"
////        print(urlStr)
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确json格式")
////                return
////            }
////            
////            //  代码执行到此字典一定有值
////            
////            let name = dic["name"]
////            let avatar_large = dic["avatar_large"]
////            
////            //  设置用户名和头像
////            userAccount.name = name as? String
////            userAccount.avatar_large = avatar_large as? String
////            
////            print(userAccount)
////            }) { (_, error) -> Void in
////              print(error)
////        }
//        
//        
//    }
    


}

extension CZOAuthViewController: UIWebViewDelegate {
    
    //  将要加载请求  http://www.itcast.cn/?code=f6cea50fbbf21cc1c7ce4a3030966afe
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return false
        }
        
        //  代码执行到此,我们的url一定有值
        //  获取url的绝对地址
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }

        print(url.absoluteString)
        //  代码执行到此就是我们需要关心的url字符串
        
        if let query = url.query where query.hasPrefix("code=") {
            //  截取code
            let code = query.substringFromIndex("code=".endIndex)
            
            print("我想要的code: " + code)
            
//            requestAccesstoken(code)
            
            CZUserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //  发送通知,释放资源
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                    
                } else {
                    print("登录失败")
                }
            })
            
            
        } else {
            //  进入取消回调页
            dismissViewControllerAnimated(true, completion: nil)
            
            
        }
  
        
        
        
        
        

        return false
        
    }
    
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}























